package com.yami.shop.events.orderEvent;

import com.yami.shop.bean.enums.UserFundDetailEnum;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.model.UserFundDetail;
import com.yami.shop.service.OrderItemService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.UserFundDetailService;
import com.yami.shop.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

//@Component 禁用
public class EventListener {
    @Autowired
    private OrderService orderService;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UserService userService;

    @Autowired
    private UserFundDetailService userFundDetailService;

    @Autowired
    private OrderItemService orderItemService;

    @Async
    @org.springframework.context.event.EventListener
    @Transactional
    public void handleMyEvent(Event event) {
        Long id = event.getId();
        Integer status = event.getStatus();

        if(status == 0){
            //订单收货成功
            Order byId = orderService.getById(id);
            if(byId == null){
                throw new RuntimeException("订单收货成功 事件 查询订单为空");
            }

            System.out.println("收货成功");

            //下单用户
            User byId0 = userService.getById(byId.getUserId());

            if(byId0 == null){
                return;
            }

            String enableDistributionProdIds = this.getValueByConfig("enable_distribution_prod_ids");
            List<String> prodIds = Arrays.asList(StringUtils.split(enableDistributionProdIds, ","));

            List<OrderItem> oi = orderItemService.lambdaQuery().eq(OrderItem::getOrderNumber, byId.getOrderNumber()).list();
            List<String> collect = oi.stream().map(o -> o.getProdId()).map(p -> String.valueOf(p)).collect(Collectors.toList());

            //在用户下单的订单中,找是否存在开启分销的商品
            List<String> collect1 = collect.stream().filter(op -> prodIds.contains(op)).collect(Collectors.toList());

            if(!collect1.isEmpty()){
//一级分销用户
                User byId1 = userService.getById(byId0.getHigherLevelUid());
                if(byId1 != null){
                    String level1 = this.getValueByConfig("level1");

                    BigDecimal distributionBonus = byId1.getDistributionBonus();

                    if( distributionBonus == null){
                        distributionBonus = BigDecimal.ZERO;
                    }

                    BigDecimal add = distributionBonus.add(new BigDecimal(level1));

                    User user = new User();
                    user.setUserId(byId1.getUserId());
                    user.setDistributionBonus(add);
                    userService.updateById(user);

                    UserFundDetail detail=new UserFundDetail();
                    detail.setUserType("tz_user");
                    detail.setUid(byId1.getUserId());
                    detail.setCategory(UserFundDetailEnum.DISTRIBUTION_BONUS.getValue());
                    detail.setType(UserFundDetailEnum.TYPE_0.getValue());
                    detail.setPm(Integer.valueOf(UserFundDetailEnum.PM_1.getValue()));
                    detail.setMoney(new BigDecimal(level1));
                    detail.setResidueMoney(add);
                    detail.setTitle("一级分销奖励");
                    detail.setDetails("一级分销奖励:"+level1 +", 剩余:"+add);
                    detail.setDelFlag(0);

                    //detail.setCreateBy(userId);
                    detail.setCreateTime(new Date());

                    userFundDetailService.save(detail);
                }

                //二级分销用户
                User byId2 = userService.getById(byId1.getHigherLevelUid());
                if(byId2 != null){
                    String level1 = this.getValueByConfig("level2");

                    BigDecimal distributionBonus = byId2.getDistributionBonus();

                    if( distributionBonus == null){
                        distributionBonus = BigDecimal.ZERO;
                    }

                    BigDecimal add = distributionBonus.add(new BigDecimal(level1));

                    User user = new User();
                    user.setUserId(byId2.getUserId());
                    user.setDistributionBonus(add);
                    userService.updateById(user);

                    UserFundDetail detail=new UserFundDetail();
                    detail.setUserType("tz_user");
                    detail.setUid(byId2.getUserId());
                    detail.setCategory(UserFundDetailEnum.DISTRIBUTION_BONUS.getValue());
                    detail.setType(UserFundDetailEnum.TYPE_1.getValue());
                    detail.setPm(Integer.valueOf(UserFundDetailEnum.PM_1.getValue()));
                    detail.setMoney(new BigDecimal(level1));
                    detail.setResidueMoney(add);
                    detail.setTitle("二级分销奖励");
                    detail.setDetails("二级分销奖励:"+level1 +", 剩余:"+add);
                    detail.setDelFlag(0);

                    //detail.setCreateBy(userId);
                    detail.setCreateTime(new Date());

                    userFundDetailService.save(detail);
                }

                //三级分销用户
                User byId3 = userService.getById(byId2.getHigherLevelUid());
                if(byId3 != null){
                    String level1 = this.getValueByConfig("level3");

                    BigDecimal distributionBonus = byId3.getDistributionBonus();

                    if( distributionBonus == null){
                        distributionBonus = BigDecimal.ZERO;
                    }

                    BigDecimal add = distributionBonus.add(new BigDecimal(level1));

                    User user = new User();
                    user.setUserId(byId3.getUserId());
                    user.setDistributionBonus(add);
                    userService.updateById(user);

                    UserFundDetail detail=new UserFundDetail();
                    detail.setUserType("tz_user");
                    detail.setUid(byId3.getUserId());
                    detail.setCategory(UserFundDetailEnum.DISTRIBUTION_BONUS.getValue());
                    detail.setType(UserFundDetailEnum.TYPE_2.getValue());
                    detail.setPm(Integer.valueOf(UserFundDetailEnum.PM_1.getValue()));
                    detail.setMoney(new BigDecimal(level1));
                    detail.setResidueMoney(add);
                    detail.setTitle("三级分销奖励");
                    detail.setDetails("三级分销奖励:"+level1 +", 剩余:"+add);
                    detail.setDelFlag(0);

                    //detail.setCreateBy(userId);
                    detail.setCreateTime(new Date());

                    userFundDetailService.save(detail);
                }
            }
        }
    }


    /**
     * 获取配置项
     * @param key
     * @return
     */
    public String  getValueByConfig(String key) {
        List<String> param_value = jdbcTemplate.query("select param_value from tz_sys_config where param_key = ? ", new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getString("param_value");
            }
        }, key);

        if(param_value.isEmpty()){
            return null;
        }else{
            return param_value.get(0);
        }
    }
}
